package com.h2cloud.Test2;


/**
 * @Package: com.h2cloud.Test2
 * @ClassName: threadPrint
 * @Author: h2cloud
 * @CreateTime: 2022/8/18 10:57 下午
 * @Description:
 */
public class threadPrint {

	Object lock = new Object();

	public static void main(String[] args) {
		WaitNotify waitNotify = new WaitNotify(1, 5);

		new Thread(() -> {
			waitNotify.print(1, 2, 1);

		}, "a线程").start();

		new Thread(() -> {
			waitNotify.print(2, 3, 2);

		}, "b线程").start();

		new Thread(() -> {
			waitNotify.print(3, 1, 3);

		}, "c线程").start();

	}

	static class WaitNotify {
		int flag;
		int loopNumber;

		public WaitNotify(int flag, int loopNumber) {
			this.flag = flag;
			this.loopNumber = loopNumber;
		}

		/*打印*/
		public void print(int str, int waitFlag, int nextFlag) {
			for (int i = 0; i < loopNumber; i++) {
				synchronized (this) {
					while (waitFlag != this.flag) {
						try {
							this.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					System.out.print(str);
					this.flag = nextFlag;
					this.notifyAll();
				}
			}
		}
	}
}

